# coding:utf8
from datetime import datetime
import os
import time


def run_monkey (package,Path):
    date = monkey_date()
    path = Path+str(date)
    print('-------开始执行monkey-------')
    try:
        os.popen("adb shell monkey -s 5055 -p {} --ignore-crashes --ignore-timeouts --ignore-security-exceptions --ignore-native-crashes --monitor-native-crashes --throttle 800   --pct-motion 100  -v -v -v 6000000 >{}.txt".format(package,path))

    except :
            print('monkey执行异常')

def get_monkey_pid():
    monkey_pid = os.popen('adb shell ps | findstr monkey')
    try:
        pid = monkey_pid.readline().split()[1]
        return pid
    except:
        return 'monkey_erro'


def kill_monkey():

    while True:
        monkey_pid = get_monkey_pid()
        if monkey_pid != 'monkey_erro':
            os.popen('adb shell kill {}'.format(monkey_pid))
            print('monkey进程已杀死')
        elif monkey_pid == 'monkey_erro':
            break

def time_monkey(times,package,path):
    times = times*60
    start_time = time.time()
    run_monkey(package,path)
    time.sleep(times)
    end_time = time.time()
    execution_time = end_time-start_time
    if execution_time >= times:
        kill_monkey()
def  monkey_date():
    datetimes = datetime.now()
    return datetimes
def aaa(path):
    date = monkey_date()
    path = path + str(date)
    print(f'adb shell {path}.txt')






if __name__ == '__main__':
    # run_monkey('com.dianzhong.reader','"D:\\xingneng\\monkey.txt"')
    # kill_monkey()
    time_monkey(60,'com.dianzhong.reader','D:\\monkey\\monkey_script\\logs\\monkey_log_')
    # monkey_date()monkey_date
    # aaa('D:\\monkey\\monkey_script\\logs\\monkey_log_')